// store/tagsView.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export interface TagView {
  path: string
  name: string
  title: string
  fullPath: string
}

export const useTagsViewStore = defineStore('tagsView', () => {
  const router = useRouter()
  const route = useRoute()

  const storedViews = JSON.parse(localStorage.getItem('visitedViews') || '[]')
  const visitedViews = ref<TagView[]>([])

  // 添加标签（去重）
  const addView = (view: TagView) => {
    if (visitedViews.value.some(v => v.path === view.path)) return
    visitedViews.value.push(view)
    saveToLocalStorage()
  }

  // 删除标签
  const delView = (view: TagView) => {
    visitedViews.value = visitedViews.value.filter(v => v.path !== view.path)
    saveToLocalStorage()
    if (view.path === route.path) {
      const latestView = visitedViews.value.slice(-1)[0]
      if (latestView) {
        router.push(latestView.path)
      } else {
        router.push('/dashboard') // 回到控制台
      }
    }
  }

  // 关闭其他标签
  const delOthersViews = (view: TagView) => {
    visitedViews.value = visitedViews.value.filter(v => v.path === view.path || v.path === '/dashboard')
    saveToLocalStorage()
  }

  // 关闭所有标签
  const delAllViews = () => {
    visitedViews.value = []
    addView({
      path: '/dashboard',
      name: 'Dashboard',
      title: '控制台',
      fullPath: '/dashboard'
    })
    saveToLocalStorage()
    router.push('/dashboard')
  }

  // 判断是否激活
  const isActive = (tag: TagView) => {
    return tag.path === route.path
  }

  // 初始化：添加“控制台”标签
  const initTags = () => {
    const dashboard: TagView = {
      path: '/dashboard',
      name: 'Dashboard',
      title: '控制台',
      fullPath: '/dashboard'
    }
    if (storedViews.length === 0) {
      visitedViews.value = [dashboard]
    } else {
      visitedViews.value = storedViews
    }
    saveToLocalStorage()
  }

  // 路由切换后自动添加标签
  router.afterEach((to) => {
    if (to.meta.showInMenu === false) return // 不显示的菜单不加标签
    const title = to.meta.title as string || to.name as string || '未知页面'
    const view: TagView = {
      path: to.path,
      name: to.name as string,
      title,
      fullPath: to.fullPath
    }
    addView(view)
  })

  // 保存到 localStorage
  const saveToLocalStorage = () => {
    localStorage.setItem('visitedViews', JSON.stringify(visitedViews.value))
  }

  return {
    visitedViews,
    addView,
    delView,
    delOthersViews,
    delAllViews,
    isActive,
    initTags
  }
})